<template>
    <el-form :model="userForm" ref="userForm" label-width="100px" style="margin-top:20px;">
        <el-form-item
            label="User Name"
            prop="username"
            :rules="[
                            {required:true, message: $t('message.required'), trigger:'blur'}
                            ]"
        >
            <el-input v-model="userForm.username" v-on:keyup.enter.native="$refs.userForm_password.$el.querySelector('input').focus()"></el-input>
        </el-form-item>
        <el-form-item
            label="Password"
            prop="password"
            :rules="[
                            {required:true, message: $t('message.required'), trigger:'blur'}
                            ]"
        >
            <el-input type="password" v-model="userForm.password" ref="userForm_password" autocomplete="off" v-on:keyup.enter.native="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">{{ $t('button.confirm') }}</el-button>
            <el-button @click="$refs['userForm'].resetFields()">{{ $t('button.cancel') }}</el-button>
        </el-form-item>
    </el-form>
</template>

<script >
import Vue from "vue";

export default {
    name: `login`,
    props: {},
    data: function() {
        return {
            userForm: {
                username: ``,
                password: ``
            }
        };
    },
    mounted: function() {
        this.$store.state.activeIndex = `/ui/admin`;
    },
    methods: {
        onSubmit() {

            const formData = new FormData(this.$refs.userForm.$el);
            formData.append(`username`, this.userForm.username);
            formData.append(`password`, this.userForm.password);

            Vue.axios({
                method: `POST`,
                url: `/login`,
                data: formData
            })
                .then(response => {
                    if (response.status === 200) {
                        this.$router.push("/ui/admin");
                        return;
                    }
                    throw error;
                })
                .catch(error => {
                    this.$message({
                        type: `error`,
                        message: 'login failed'
                    });
                    this.$router.push("/ui/login");
                });
        }
    }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus"></style>
